// pages/backlog/backlog.js
let app = getApp();
const util = require("../../utils/util.js");
import { formatDate } from "../../utils/formatDate.js";
import {
  billAccountsApi,
  getSettledHistoryApi,
  getParkBillListApi,
} from "../../api/index.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageAllHeight: app.globalData.pageAllHeight - 320,
    date: util.formatDates(new Date())[0], //获取当前月份
    parkName: "请选择车场名称",
    parkColumns: wx.getStorageSync("parkColumns"),
    parkId: "",
    settleHistoryListDetail: {},
    selectedData: {},
    selected: 0,
    payType: 0,
    billList: {
      dayList: [],
    },
    settleInfo: {}, //弹窗结算信息
    showSettlement: false,
    settlementRadio: "2",
    billStatus: 0,
    pageNum: 1,
    pageSize: 10,
    pageFlag: false,
    disabled: false,
    zmStatus: 0,
    firstAndLastTime: util.getFirstAndLastDay(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let parkId = wx.getStorageSync("parkId") ? wx.getStorageSync("parkId") : "";
    this.setData({ parkId });
  },
  onShow() {
    // 查询已审核通过车场
    let selectPark = this.selectComponent("#selectPark"); // 页面获取自定义组件实例
    selectPark.getAuditedPark(); // 通过实例调用组件事件
    this.setData({
      parkColumns: wx.getStorageSync("parkColumns")
        ? wx.getStorageSync("parkColumns")
        : [],
      parkId: wx.getStorageSync("parkId") ? wx.getStorageSync("parkId") : "",
    });
    this.getBillList();
  },

  // 日期改变出发事件
  changeDate(e) {
    this.setData({
      "firstAndLastTime.startTime": e.detail.startTimestamp,
      "firstAndLastTime.endTime": e.detail.endTimestamp,
    });
    this.getBillList();
  },
  // 选择停车场
  bindChangeParkName(e) {
    const { parkId, parkName } = e.detail;
    this.setData({
      parkName,
      parkId,
    });
    this.getBillList();
  },
  // 跳转账单详情
  toBillDetail(e) {
    const item = e.detail;
    item.billStatus = this.data.billStatus;
    wx.navigateTo({
      url:
        "/pages/reconciliationDetails/reconciliationDetails?item=" +
        JSON.stringify(item),
    });
  },
  // 已结算账单详情
  toSettleBillDetail(e) {
    const { item } = e.currentTarget.dataset;
    item.zmStatus = 2;
    wx.navigateTo({
      url:
        "/pages/reconciliationDetails/reconciliationDetails?item=" +
        JSON.stringify(item),
    });
  },

  // tab切换
  bindChangeTab(e) {
    this.setData({
      billStatus: e.detail.index,
      settledStatus: e.detail.index,
    });
    const { index } = e.detail;
    if (index == 1) {
      this.setData({
        zmStatus: 1,
      });
      this.getBillList();
    } else {
      this.setData({
        zmStatus: 0,
      });
      this.getBillList();
    }
  },
  //   结算
  async settleAccounts(e) {
    try {
      const {
        payType,
        parkFund,
        unsettledAmount,
        discountFund,
      } = e.currentTarget.dataset.item;
      if (payType === 1) {
        if (unsettledAmount > parkFund) {
          getApp().showToast("余额不足");
          return false;
        }
      }
      if (payType === 2) {
        if (unsettledAmount > discountFund) {
          getApp().showToast("余额不足");
          return false;
        }
      }
      await billAccountsApi({
        parkId: this.data.parkId,
        method: payType || 0,
      });
      wx.showModal({
        title: "提示",
        content:
          "已提交申请,平台正在审核,会在3个工作日内处理,如有疑问,请联系031185118730",
        showCancel: false,
        complete: (res) => {
          if (res.confirm) {
            this.getBillList();
          }
        },
      });
    } catch (error) {}
  },
  //   拨号
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.serviceTel,
    });
  },
  goReconciliationDetail(e) {
    const { type } = e.currentTarget.dataset;
    const { parkName, parkId } = this.data;
    let item = {
      parkName: parkName,
      parkId,
      type,
    };
    wx.navigateTo({
      url:
        "/pages/reconciliationDetails/reconciliationDetails?item=" +
        JSON.stringify(item),
    });
  },
  //   查询未结算车费和通行券余额 getBillListApi
  async getBillList() {
    try {
      const { firstAndLastTime, parkId, zmStatus, billStatus } = this.data;
      const { data: res } = await getParkBillListApi({
        parkId,
        startTime: firstAndLastTime.startTime,
        endTime: firstAndLastTime.endTime,
        zmStatus: billStatus,
      });
      // console.log("查询未结算车费和通行券余额", res.data);
      res.data.dayList.forEach((item) => {
        item.billTime = formatDate(item.billTime);
      });
      this.setData({
        billList: res.data,
      });
    } catch (error) {}
  },
  //   结算历史
  async getSettledHistory(next) {
    const {
      parkId,
      pageNum,
      pageSize,
      settleHistoryList,
      startTime,
      endTime,
    } = this.data;
    const { data: res } = await getSettledHistoryApi({
      parkId,
      startTime,
      endTime,
      pageNum: pageNum,
      pageSize,
    });
    const newsettleHistoryList = next
      ? settleHistoryList.concat(res.data.records)
      : res.data.records;
    this.setData({
      settleHistoryList: newsettleHistoryList,
      pageFlag: !res.data.records.length && next,
    });
  },
  // 触底事件函数
  scrollToLower() {
    const { pageFlag } = this.data;
    if (!pageFlag) {
      this.setData({ pageNum: this.data.pageNum + 1 });
      this.getSettledHistory(true);
    }
  },
  selectItem: function (e) {
    const { index, item } = e.currentTarget.dataset;
    this.setData({
      selected: index,
      selectedData: item,
    });
  },
  // 打开结算弹窗
  showSettlementPopup(e) {
    const { discountFund, unsettledAmount } = e.detail;
    if (discountFund < unsettledAmount && discountFund > 0) {
      wx.showModal({
        title: "提示",
        content: `余额不足,仅限支付${discountFund}元,未结部分下次结清`,
        confirmText: "去结算",
        complete: (res) => {
          if (res.confirm) {
            if (discountFund != 0) {
              this.setData({
                disabled: true,
                showSettlement: true,
                settleInfo: e.detail,
              });
            }
          }
        },
      });
      return;
    }
    if (discountFund != 0) {
      this.setData({
        disabled: true,
        showSettlement: true,
        settleInfo: e.detail,
      });
      return;
    }
    this.setData({
      showSettlement: true,
      settleInfo: e.detail,
    });
  },
  onCloseSettlement() {
    this.setData({
      showSettlement: false,
    });
  },
  onChangeSettlement(event) {
    this.setData({
      settlementRadio: event.detail,
    });
  },
  // 切换结算方式
  onClickSettlement(event) {
    if (this.data.settleInfo.discountFund != 0) {
      return;
    }
    const { name } = event.currentTarget.dataset;
    this.setData({
      settlementRadio: name,
    });
  },
  // 弹窗确认结算
  async onClickSettlementBtn() {
    const payType = this.data.settlementRadio;
    const { gid, discountFund } = this.data.settleInfo;
    if (payType == 2 && discountFund === 0) {
      wx.showModal({
        title: "提示",
        content: "余额不足，请您出售通行券",
        confirmText: "去出售",
        complete: (res) => {
          if (res.confirm) {
            this.setData({
              showSettlement: false,
            });
            wx.switchTab({
              url: "/pages/parkCoupon/parkCoupon",
            });
          }
        },
      });
      return;
    }
    await billAccountsApi({
      gid,
      payType,
      parkId: this.data.parkId,
    });
    this.onCloseSettlement();
    wx.showModal({
      title: "提示",
      content: "结算成功,请注意查收",
      showCancel: false,
      complete: (res) => {
        if (res.confirm) {
          this.setData({
            disabled: false,
          });
          this.getBillList();
        }
      },
    });
    return;
  },
});
